package com.wekatest;

/*import org.junit.jupiter.api.Test;
import weka.associations.Apriori;
import weka.classifiers.AbstractClassifier;
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.classifiers.bayes.NaiveBayes;
import weka.classifiers.bayes.NaiveBayesUpdateable;
import weka.classifiers.evaluation.NumericPrediction;
import weka.classifiers.functions.LibSVM;
import weka.classifiers.functions.MultilayerPerceptron;
import weka.classifiers.lazy.IBk;
import weka.classifiers.meta.MultiClassClassifier;
import weka.classifiers.timeseries.WekaForecaster;
import weka.classifiers.timeseries.core.OverlayForecaster;
import weka.classifiers.timeseries.eval.TSEvaluation;
import weka.classifiers.trees.DecisionStump;
import weka.classifiers.trees.J48;
import weka.classifiers.trees.M5P;
import weka.clusterers.ClusterEvaluation;
import weka.clusterers.Cobweb;
import weka.clusterers.EM;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.converters.ArffLoader;
import weka.core.converters.ConverterUtils;
import weka.core.converters.DatabaseLoader;
import weka.core.converters.DatabaseSaver;
import weka.core.pmml.jaxbbindings.Coefficient;
import weka.experiment.InstanceQuery;
import weka.filters.Filter;
import weka.filters.supervised.attribute.AddClassification;
import weka.filters.supervised.attribute.TSLagMaker;
import weka.filters.unsupervised.attribute.Remove;
import weka.filters.unsupervised.attribute.Standardize;*/

import java.io.File;
import java.math.BigDecimal;
import java.util.*;

public class WekaTest1 {

    /*private Instances loadArffFile(String arffFile) throws Exception {
        Instances instances = ConverterUtils.DataSource.read(arffFile);
        return instances;
    }

    private void saveArffFile(String newFile,Instances instances) throws Exception {
        ConverterUtils.DataSink.write(newFile,instances);
    }

    private Instances removeAttr(int index,Instances instances) throws Exception {
        Remove remove = new Remove();
        remove.setAttributeIndices(""+index);
        remove.setInputFormat(instances);
        Instances instancesNew = Filter.useFilter(instances,remove);
        return instancesNew;
    }



    @Test
    public void filterTest() throws Exception {
        WekaTest1 wekaTest1 = new WekaTest1();

        String arffFile = "E:/bi/data/weather.nominal.arff";
        Instances instances = wekaTest1.loadArffFile(arffFile);

        Instances instancesRM = wekaTest1.removeAttr(1,instances);
        //System.out.println(instancesRM);

        String newFile = "E:/bi/data/weather.nominal.1.arff";
        wekaTest1.saveArffFile(newFile,instancesRM);

        Instances instancesRandom = new Instances(instances);
        instancesRandom.randomize(new Random());
        System.out.println(instancesRandom);
    }

    @Test
    public void batchFilteringTest() throws Exception {
        Instances train = ConverterUtils.DataSource.read("E:/bi/data/segment-challenge.arff");
        Instances test = ConverterUtils.DataSource.read("E:/bi/data/segment-test.arff");

        Standardize filter = new Standardize();
        filter.setInputFormat(train);
        Instances trainNew = Filter.useFilter(train,filter);
        Instances testNew = Filter.useFilter(test,filter);

        //System.out.println(trainNew);
        //System.out.println(testNew);
        ConverterUtils.DataSink.write("E:/bi/data/segment-train-new.arff",trainNew);
        ConverterUtils.DataSink.write("E:/bi/data/segment-test-new.arff",testNew);
    }


    @Test
    public void batchClassifierTest() throws Exception {
        String arffFile = "E:/bi/data/weather.nominal.arff";
        Instances instances = ConverterUtils.DataSource.read(arffFile);
        instances.setClassIndex(instances.numAttributes()-1);

        //训练J48分类器
        J48 j48 = new J48();
        j48.setUnpruned(true);
        j48.buildClassifier(instances);
        System.out.println("======j48=======");
        System.out.println(j48);

        //
        NaiveBayes naiveBayes = new NaiveBayes();
        naiveBayes.buildClassifier(instances);
        System.out.println("======naiveBayes=======");
        System.out.println(naiveBayes);

        //
        System.out.println("======naiveBayesUpdateable=======");
        ArffLoader arffLoader = new ArffLoader();
        arffLoader.setFile(new File(arffFile));

        NaiveBayesUpdateable naiveBayesUpdateable = new NaiveBayesUpdateable();
        Instances structure =  arffLoader.getStructure();
        structure.setClassIndex(structure.numAttributes()-1);
        System.out.println("======structure=======");
        System.out.println(structure);
        naiveBayesUpdateable.buildClassifier(structure);
        Instance instance;
        while ((instance=arffLoader.getNextInstance(structure)) !=null){
            naiveBayesUpdateable.updateClassifier(instance);
        }
        System.out.println("======naiveBayesUpdateable=======");
        System.out.println(naiveBayesUpdateable);
        System.out.println();

    }


    *//**
     * pridict test instances class type by j48
     *//*
    @Test
    public void outputClassDistribution() throws Exception{
        Instances train = ConverterUtils.DataSource.read("E:/bi/data/segment-challenge.arff");
        Instances test = ConverterUtils.DataSource.read("E:/bi/data/segment-test.arff");
        train.setClassIndex(train.numAttributes()-1);
        test.setClassIndex(test.numAttributes()-1);
        if(!train.equalHeaders(test)){
            throw  new Exception("head error!");
        }

        //training J48
        J48 j48 = new J48();
        j48.buildClassifier(train);

        for(int i=0;i<test.numInstances();i++){
            Instance testInstance = test.instance(i);
            //得到预测
            double pred = j48.classifyInstance(testInstance);
            //得到分布
            double[] dist = j48.distributionForInstance(testInstance);

            System.out.print(pred);
            System.out.print(" == ");
            System.out.println(test.classAttribute().value((int)pred));
        }


        //Evaluation
        Evaluation evaluation = new Evaluation(train);
        evaluation.evaluateModel(j48,test);
        System.out.println(evaluation.toSummaryString());

    }




    *//**
     * pridict test instances class type by j48
     *//*
    @Test
    public void runOneCV() throws Exception{

        String arffFile = "E:/bi/data/ionosphere.arff";
        Instances instances = ConverterUtils.DataSource.read(arffFile);
        instances.setClassIndex(instances.numAttributes()-1);

        //J48分类器
        J48 classifier = new J48();
        //j48.setUnpruned(true);

        int seed = 1234;
        int folds = 10;

        Random random = new Random(seed);
        Instances newData = new Instances(instances);
        newData.randomize(random);
        if(newData.classAttribute().isNominal()){
            newData.stratify(folds);
        }

        Instances predictedData = null;
        Evaluation evaluation = new Evaluation(newData);
        for(int i=0;i<folds;i++){
            Instances train = newData.trainCV(folds,i);//划1折出来，其他作训练集
            Instances test = newData.testCV(folds,i);//划1折作测试集

            Classifier classifierCopy = AbstractClassifier.makeCopy(classifier);
            classifierCopy.buildClassifier(train);
            evaluation.evaluateModel(classifierCopy,test);

            AddClassification addClassificationFilter = new AddClassification();
            addClassificationFilter.setClassifier(classifier);
            addClassificationFilter.setOutputClassification(true);
            addClassificationFilter.setOutputDistribution(true);
            addClassificationFilter.setOutputErrorFlag(true);
            addClassificationFilter.setInputFormat(train);
            //训练分类器
            Filter.useFilter(train,addClassificationFilter);
            //predict
            Instances pred = Filter.useFilter(test,addClassificationFilter);
            if(predictedData == null) {
                predictedData = new Instances(pred,0);
            }

            for(int j=0;j<pred.numInstances();j++){
                predictedData.add(pred.instance(j));
            }


        }
        System.out.println(predictedData);

        System.out.println(evaluation.toSummaryString());

    }



    @Test
    public void batchClusterer() throws Exception{
        String arffFile = "E:/bi/data/contact-lenses.arff";
        Instances instances = ConverterUtils.DataSource.read(arffFile);

        EM cluster = new EM();
        String options = "-I 100";
        cluster.setOptions(options.split(" "));
        cluster.buildClusterer(instances);
        System.out.println(cluster);

        ClusterEvaluation clusterEvaluation = new ClusterEvaluation();
        clusterEvaluation.setClusterer(cluster);
        clusterEvaluation.evaluateClusterer(instances);
        System.out.println(clusterEvaluation.clusterResultsToString());
    }


    @Test
    public void incrementalCluster() throws Exception{

        String arffFile = "E:/bi/data/contact-lenses.arff";
        ArffLoader arffLoader = new ArffLoader();
        arffLoader.setFile(new File(arffFile));
        Instances structure = arffLoader.getStructure();

        Cobweb cluster = new Cobweb();
        cluster.buildClusterer(structure);
        Instance current;
        while ((current = arffLoader.getNextInstance(structure))!=null){
            cluster.updateClusterer(current);
        }
        cluster.updateFinished();

        System.out.println(cluster);
    }


    @Test
    public void batchClassifierTest_IBk() throws Exception {
        String arffFile = "E:/bi/data/glass.arff";
        Instances instances = ConverterUtils.DataSource.read(arffFile);
        instances.setClassIndex(instances.numAttributes()-1);

        IBk iBk = new IBk();
        iBk.buildClassifier(instances);
        System.out.println("======iBk=======");
        System.out.println(iBk);

        int seed = 1234;
        int folds = 10;

        Random random = new Random(seed);
        Instances newData = new Instances(instances);
        newData.randomize(random);
        if(newData.classAttribute().isNominal()){
            newData.stratify(folds);
        }

        Instances predictedData = null;
        Evaluation evaluation = new Evaluation(newData);
        for(int i=0;i<folds;i++){
            System.out.println();
            Instances train = newData.trainCV(folds,i);//划1折出来，其他作训练集
            Instances test = newData.testCV(folds,i);//划1折作测试集

            Classifier classifierCopy = AbstractClassifier.makeCopy(iBk);
            classifierCopy.buildClassifier(train);
            evaluation.evaluateModel(classifierCopy,test);

            AddClassification addClassificationFilter = new AddClassification();
            addClassificationFilter.setClassifier(iBk);
            addClassificationFilter.setOutputClassification(true);
            addClassificationFilter.setOutputDistribution(true);
            addClassificationFilter.setOutputErrorFlag(true);
            addClassificationFilter.setInputFormat(train);
            //训练分类器
            Filter.useFilter(train,addClassificationFilter);
            //predict
            Instances pred = Filter.useFilter(test,addClassificationFilter);
            if(predictedData == null) {
                predictedData = new Instances(pred,0);
            }

            for(int j=0;j<pred.numInstances();j++){
                predictedData.add(pred.instance(j));
            }


        }
        System.out.println(predictedData);

        System.out.println(evaluation.toSummaryString());

    }

    @Test
    public void batchClassifierTest_Meta() throws Exception {
        String arffFile = "E:/bi/data/iris.arff";
        Instances instances = ConverterUtils.DataSource.read(arffFile);
        instances.setClassIndex(instances.numAttributes()-1);

        DecisionStump decisionStump = new DecisionStump();
*//*

        //meta
        System.out.println("======AdaBoostM1========");
        AdaBoostM1 adaBoostM1 = new AdaBoostM1();
        adaBoostM1.setClassifier(decisionStump);
        adaBoostM1.buildClassifier(instances);
        System.out.println(adaBoostM1);

        Evaluation evaluation = new Evaluation(instances);
        evaluation.crossValidateModel(adaBoostM1,instances,10, new Random(1234));
        System.out.println(evaluation.toSummaryString());



        System.out.println("======J48========");
        J48 j48 = new J48();
        j48.buildClassifier(instances);
        System.out.println(j48);

        Evaluation evaluation1 = new Evaluation(instances);
        evaluation1.crossValidateModel(j48,instances,10, new Random(1234));
        System.out.println(evaluation1.toSummaryString());
*//*



        System.out.println("======LibSVM========");
        LibSVM libSVM = new LibSVM();
        libSVM.buildClassifier(instances);
        System.out.println(libSVM);

        Evaluation evaluation2 = new Evaluation(instances);
        evaluation2.crossValidateModel(libSVM,instances,10, new Random(1234));
        System.out.println(evaluation2.toSummaryString());
    }

    String url = "jdbc:mysql://127.0.0.1:3307/weka?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&pinGlobalTxToPhysicalConnection=true&useSSL=false";
    String username = "root";
    String password = "laoliou";

    @Test
    public void loadDataFromDB() throws Exception {
        InstanceQuery query = new InstanceQuery();

        query.setDatabaseURL(url);
        query.setUsername(username);
        query.setPassword(password);
        query.setQuery("select * from weather");
        Instances instances = query.retrieveInstances();
        instances.setClassIndex(instances.numAttributes()-1);
        System.out.println(instances);

        System.out.println("======J48========");
        J48 j48 = new J48();
        j48.buildClassifier(instances);
        System.out.println(j48);

        Evaluation evaluation1 = new Evaluation(instances);
        evaluation1.crossValidateModel(j48,instances,10, new Random(1234));
        System.out.println(evaluation1.toSummaryString());

        System.out.println("======LibSVM========");
        LibSVM libSVM = new LibSVM();
        libSVM.buildClassifier(instances);
        System.out.println(libSVM);

        Evaluation evaluation2 = new Evaluation(instances);
        evaluation2.crossValidateModel(libSVM,instances,10, new Random(1234));
        System.out.println(evaluation2.toSummaryString());
    }


    @Test
    public void loadDataFromDB1() throws Exception {

        DatabaseLoader databaseLoader = new DatabaseLoader();
        databaseLoader.setSource(url,username,password);
        databaseLoader.setQuery("select * from weather");
        Instances instances = databaseLoader.getDataSet();

        instances.setClassIndex(instances.numAttributes()-1);
        System.out.println(instances);

        System.out.println("======J48========");
        J48 j48 = new J48();
        j48.buildClassifier(instances);
        System.out.println(j48);

        Evaluation evaluation1 = new Evaluation(instances);
        evaluation1.crossValidateModel(j48,instances,10, new Random(1234));
        System.out.println(evaluation1.toSummaryString());

        System.out.println("======LibSVM========");
        LibSVM libSVM = new LibSVM();
        libSVM.buildClassifier(instances);
        System.out.println(libSVM);

        Evaluation evaluation2 = new Evaluation(instances);
        evaluation2.crossValidateModel(libSVM,instances,10, new Random(1234));
        System.out.println(evaluation2.toSummaryString());
    }




    @Test
    public void saveDataToDB() throws Exception {
        String arffFile = "E:/bi/data/iris.arff";
        Instances instances = ConverterUtils.DataSource.read(arffFile);

        DatabaseSaver databaseSaver = new DatabaseSaver();
        databaseSaver.setDestination(url,username,password);
        databaseSaver.setTableName("iris");
        databaseSaver.setRelationForTableName(false);
        databaseSaver.setInstances(instances);
        databaseSaver.writeBatch();
    }


    @Test
    public void saveDataToDB1() throws Exception {
        String arffFile = "E:/bi/data/supermarket.arff";
        Instances instances = ConverterUtils.DataSource.read(arffFile);

        Remove rm = new Remove();
        int[] ii = new int[]{0,1,2,3,4,5,6,7,8,10,78,79,80,87,88,97,99,100,101,106,107,108,109,110,111,112,113,115,116,117,118,119,121,122,123,124,125,126,127,128,129,
                136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173};
        rm.setAttributeIndicesArray(ii);
        rm.setInputFormat(instances);
        Instances instancesRM = Filter.useFilter(instances,rm);

        System.out.println(instancesRM);


        DatabaseSaver databaseSaver = new DatabaseSaver();
        databaseSaver.setDestination(url,username,password);
        databaseSaver.setTableName("supermarket");
        databaseSaver.setRelationForTableName(false);
        databaseSaver.setInstances(instancesRM);
        databaseSaver.writeBatch();
    }



    @Test
    public void saveBigDataToDB() throws Exception {
        String arffFile = "";
        arffFile = "E:/bi/data/wine.arff";
        Instances instances = ConverterUtils.DataSource.read(arffFile);

        DatabaseSaver databaseSaver = new DatabaseSaver();
        databaseSaver.setDestination(url,username,password);
        databaseSaver.setTableName("wine");
        databaseSaver.setRelationForTableName(false);
        databaseSaver.setRetrieval(DatabaseSaver.INCREMENTAL);
        databaseSaver.setStructure(instances);
        for(int i=0;i<instances.numInstances();i++){
            databaseSaver.writeIncremental(instances.get(i));
        }
    }


    @Test
    public void saveBigDataToDB_vote() throws Exception {
        String arffFile = "";
        arffFile = "E:/bi/data/vote.arff";
        Instances instances = ConverterUtils.DataSource.read(arffFile);

        DatabaseSaver databaseSaver = new DatabaseSaver();
        databaseSaver.setDestination(url,username,password);
        databaseSaver.setTableName("vote");
        databaseSaver.setRelationForTableName(false);
        databaseSaver.setRetrieval(DatabaseSaver.INCREMENTAL);
        databaseSaver.setStructure(instances);
        for(int i=0;i<instances.numInstances();i++){
            databaseSaver.writeIncremental(instances.get(i));
        }
    }



    @Test
    public void associate() throws Exception {
        DatabaseLoader databaseLoader = new DatabaseLoader();
        databaseLoader.setSource(url,username,password);
        databaseLoader.setQuery("select * from supermarket");
        Instances instances = databaseLoader.getDataSet();

        Apriori apriori = new Apriori();
        apriori.buildAssociations(instances);
        System.out.println(apriori);
    }



    @Test
    public void associateVote() throws Exception {
        DatabaseLoader databaseLoader = new DatabaseLoader();
        databaseLoader.setSource(url,username,password);
        databaseLoader.setQuery("select * from vote");
        Instances instances = databaseLoader.getDataSet();
        System.out.println(instances);

        Apriori apriori = new Apriori();
        apriori.buildAssociations(instances);
        System.out.println(apriori);
    }


    @Test
    public void loadDataFromDB_appleStocks2011() throws Exception {

        InstanceQuery query = new InstanceQuery();
        query.setDatabaseURL(url);
        query.setUsername(username);
        query.setPassword(password);
        query.setQuery("select * from applestocks2011");
        Instances instances = query.retrieveInstances();
        System.out.println(instances);

    }



    public final String COEF = "coef";//系数
    public final String VAR = "var";//系数
    @Test
    public void mode1(){
        BigDecimal result=new BigDecimal(0);
        StringBuffer formulaSB = new StringBuffer();

        //init data
        List<Map<String,String>> list = new ArrayList<Map<String, String>>();
        initData(list);

        //test
        String strDate = "2013-04-01";
        BigDecimal dateRemapped = new BigDecimal(15);
        List<BigDecimal> lagList = new ArrayList<BigDecimal>();
        lagList.add(new BigDecimal(2985));//lag_1
        lagList.add(new BigDecimal(2934));//lag_2
        lagList.add(new BigDecimal(2285));
        lagList.add(new BigDecimal(3795));
        lagList.add(new BigDecimal(3661));
        lagList.add(new BigDecimal(3816));
        lagList.add(new BigDecimal(3932));
        lagList.add(new BigDecimal(4426));
        lagList.add(new BigDecimal(5225));
        lagList.add(new BigDecimal(4216));
        lagList.add(new BigDecimal(3756));
        lagList.add(new BigDecimal(3111));

        Date date = DateUtils.parseDate(strDate);
        String monthStr = DateUtils.transformMonth2EN(DateUtils.getMonth(date));
        String quarterStr = DateUtils.transformQuarter2EN(DateUtils.getSeason(date));

        for(Map<String,String> map:list){
            String coef = map.get(COEF);

            //"Month=mar,oct,apr,sep,nov,dec,may,jun,aug,jul"
            //"Quarter=Q2,Q3"
            //"Lag_Fortified-4"
            //"Date-remapped*Lag_Fortified-1"
            String var = map.get(VAR);
            BigDecimal varBD = new BigDecimal(0);

            //"Month=mar,oct,apr,sep,nov,dec,may,jun,aug,jul"
            //"Quarter=Q2,Q3"
            if(var.contains("=")) {
                String[] varArr = var.split("=");
                //month
                if (varArr[0].equalsIgnoreCase("month")) {
                    if (varArr[1].contains(monthStr)) {
                        varBD = new BigDecimal(1);
                    }
                }
                //quarter
                if (varArr[0].equalsIgnoreCase("quarter")) {
                    if (varArr[1].contains(quarterStr)) {
                        varBD = new BigDecimal(1);
                    }
                }
            }

            //var = "Lag_Fortified-4"
            if(var.contains("Lag_") && var.contains("-") && !var.contains("*")){
                int i=Integer.parseInt(var.split("-")[1]) -1;
                BigDecimal lagBD = lagList.get(i);
                varBD = lagBD;
            }
            //var = "Date-remapped*Lag_Fortified-1"
            if(var.contains("Lag_") && var.contains("-") && var.contains("*")){
                int i=Integer.parseInt(var.split("-")[2]) -1;
                BigDecimal lagBD = lagList.get(i);
                varBD = lagBD.multiply(dateRemapped);
            }
            //常量
            if(var.equalsIgnoreCase("1")){
                varBD = new BigDecimal(1);
            }

            //calculate
            if(formulaSB.length() != 0){
                formulaSB.append("+");
            }
            formulaSB.append(coef).append("*").append(varBD.toString());
            result = new BigDecimal(coef).multiply(varBD).add(result);

        }











        System.out.println(formulaSB.toString());
        System.out.println(result.doubleValue());

    }


    private void initData(List<Map<String,String>> list){

        Map<String,String> map;
        //1
        map = new HashMap<String, String>();
        map.put(COEF,"308.4439");
        map.put(VAR,"Month=mar,oct,apr,sep,nov,dec,may,jun,aug,jul");
        list.add(map);
        //2
        map = new HashMap<String, String>();
        map.put(COEF,"496.514");
        map.put(VAR,"Month=nov,dec,may,jun,aug,jul");
        list.add(map);
        //3
        map = new HashMap<String, String>();
        map.put(COEF,"530.4135");
        map.put(VAR,"Month=jun,aug,jul");
        list.add(map);
        //4
        map = new HashMap<String, String>();
        map.put(COEF,"529.5535");
        map.put(VAR,"Quarter=Q4,Q2,Q3");
        list.add(map);
        //5
        map = new HashMap<String, String>();
        map.put(COEF,"-528.5641");
        map.put(VAR,"Quarter=Q2,Q3");
        list.add(map);
        //6
        map = new HashMap<String, String>();
        map.put(COEF,"613.2583");
        map.put(VAR,"Quarter=Q3");
        list.add(map);
        //7
        map = new HashMap<String, String>();
        map.put(COEF,"-0.2889");
        map.put(VAR,"Lag_Fortified-4");
        list.add(map);
        //8
        map = new HashMap<String, String>();
        map.put(COEF,"-0.1998");
        map.put(VAR,"Lag_Fortified-6");
        list.add(map);
        //9
        map = new HashMap<String, String>();
        map.put(COEF,"-0.2097");
        map.put(VAR,"Lag_Fortified-7");
        list.add(map);
        //10
        map = new HashMap<String, String>();
        map.put(COEF,"0.3532");
        map.put(VAR,"Lag_Fortified-9");
        list.add(map);
        //11
        map = new HashMap<String, String>();
        map.put(COEF,"-0.2803");
        map.put(VAR,"Lag_Fortified-10");
        list.add(map);
        //12
        map = new HashMap<String, String>();
        map.put(COEF,"0.1701");
        map.put(VAR,"Lag_Fortified-11");
        list.add(map);
        //13
        map = new HashMap<String, String>();
        map.put(COEF,"-0.0022");
        map.put(VAR,"Date-remapped*Lag_Fortified-1");
        list.add(map);
        //14
        map = new HashMap<String, String>();
        map.put(COEF,"-0.0016");
        map.put(VAR,"Date-remapped*Lag_Fortified-2");
        list.add(map);
        //15
        map = new HashMap<String, String>();
        map.put(COEF,"-0.0017");
        map.put(VAR,"Date-remapped*Lag_Fortified-3");
        list.add(map);
        //15
        map = new HashMap<String, String>();
        map.put(COEF,"0.0016");
        map.put(VAR,"Date-remapped*Lag_Fortified-4");
        list.add(map);
        //15
        map = new HashMap<String, String>();
        map.put(COEF,"0.0025");
        map.put(VAR,"Date-remapped*Lag_Fortified-7");
        list.add(map);
        map = new HashMap<String, String>();
        map.put(COEF,"-0.0017");
        map.put(VAR,"Date-remapped*Lag_Fortified-8");
        list.add(map);
        map = new HashMap<String, String>();
        map.put(COEF,"-0.003");
        map.put(VAR,"Date-remapped*Lag_Fortified-9");
        list.add(map);
        map = new HashMap<String, String>();
        map.put(COEF,"0.0026");
        map.put(VAR,"Date-remapped*Lag_Fortified-10");
        list.add(map);
        map = new HashMap<String, String>();
        map.put(COEF,"-0.0027");
        map.put(VAR,"Date-remapped*Lag_Fortified-11");
        list.add(map);
        map = new HashMap<String, String>();
        map.put(COEF,"5063.5388");
        map.put(VAR,"1");
        list.add(map);

    }




    @Test
    public void forecastWine() throws Exception{
        String arffFile = "E:/bi/data/wine.arff";
        ArffLoader arffLoader = new ArffLoader();
        arffLoader.setFile(new File(arffFile));
        Instances data = arffLoader.getDataSet();

        WekaForecaster forecaster = new WekaForecaster();
        TSLagMaker lagMaker = forecaster.getTSLagMaker();

        try {
            forecaster.setFieldsToForecast("Fortified,Dry-white");
            forecaster.setCalculateConfIntervalsForForecasts(12);
            lagMaker.setTimeStampField("Date");
            lagMaker.setMinLag(1);
            lagMaker.setMaxLag(12);
            lagMaker.setAddMonthOfYear(true);
            lagMaker.setAddQuarterOfYear(true);
            forecaster.buildForecaster(data, System.out);
            forecaster.primeForecaster(data);

            int numStepsToForecast = 4;
            List<List<NumericPrediction>> forecast =
                    forecaster.forecast(numStepsToForecast, System.out);
            String forecastString = predsToString(forecast, numStepsToForecast);
            System.out.println("------------");
            System.out.println(forecastString);
        } catch (Exception ex) {
            ex.printStackTrace();
            String msg = ex.getMessage().toLowerCase();
            if (msg.indexOf("not in classpath") > -1) {
                return;
            }
        }

    }




    @Test
    public void forecastAirline() throws Exception{
        String arffFile = "E:/bi/data/airline.arff";
        ArffLoader arffLoader = new ArffLoader();
        arffLoader.setFile(new File(arffFile));
        Instances data = arffLoader.getDataSet();

        WekaForecaster forecaster = new WekaForecaster();
        TSLagMaker lagMaker = forecaster.getTSLagMaker();

        try {
            forecaster.setFieldsToForecast("passenger_numbers");
            forecaster.setCalculateConfIntervalsForForecasts(12);
            lagMaker.setTimeStampField("Date");
            lagMaker.setMinLag(1);
            lagMaker.setMaxLag(12);
            lagMaker.setAddMonthOfYear(true);
            lagMaker.setAddQuarterOfYear(true);

            forecaster.setBaseForecaster(new M5P());//default LineRegression
            forecaster.buildForecaster(data, System.out);
            forecaster.primeForecaster(data);

            System.out.println("AlgorithmName:"+forecaster.getAlgorithmName());

            int numStepsToForecast = 4;
            List<List<NumericPrediction>> forecast =
                    forecaster.forecast(numStepsToForecast, System.out);

            String forecastString = predsToString(forecast, numStepsToForecast);
            System.out.println("------------");
            System.out.println(forecastString);

        } catch (Exception ex) {
            ex.printStackTrace();
            String msg = ex.getMessage().toLowerCase();
            if (msg.indexOf("not in classpath") > -1) {
                return;
            }
        }*/

    /*}






    //timeseriesForecasting
    @Test
    public void forecast_appleStocks2011() throws Exception{

        InstanceQuery query = new InstanceQuery();
        query.setDatabaseURL(url);
        query.setUsername(username);
        query.setPassword(password);
        query.setQuery("select Date1,Open,High,Low,Close,Volume,Adj_Close from applestocks2011 where status=1 order by Date1");
        Instances data = query.retrieveInstances();

        query.setQuery("select Date1,Open,High,Low,Close,Volume,Adj_Close from applestocks2011 where status=2 order by Date1");
        Instances overlay = query.retrieveInstances();

        WekaForecaster forecaster = new WekaForecaster();
        TSLagMaker lagMaker = forecaster.getTSLagMaker();
        List<String> overlayArray = new ArrayList<String>();
        //overlayArray.add("High");
        //overlayArray.add("Low");

        try {
            //forecaster.setBaseForecaster(new MultilayerPerceptron());
            forecaster.setFieldsToForecast("Close");
            forecaster.setCalculateConfIntervalsForForecasts(0);
            lagMaker.setOverlayFields(overlayArray);
            lagMaker.setTimeStampField("Date1");
            lagMaker.setMinLag(1);
            lagMaker.setMaxLag(12);
            lagMaker.setAddMonthOfYear(true);
            lagMaker.setAddQuarterOfYear(true);
            //lagMaker.addCustomPeriodic("Christmas==*:dec:*:*:*:*:*:*:*:*");
            forecaster.buildForecaster(data, System.out);
            forecaster.primeForecaster(data);


            int numStepsToForecast = 10;
            List<List<NumericPrediction>> forecast = forecaster.forecast(numStepsToForecast, System.out);
            //List<List<NumericPrediction>> forecast = forecaster.forecast(numStepsToForecast,overlay, System.out);

            //TSEvaluation tsEvaluation = new TSEvaluation(data,20);
            TSEvaluation tsEvaluation = new TSEvaluation(data,overlay);
            tsEvaluation.setEvaluateOnTrainingData(true);
            tsEvaluation.setEvaluationModules("MAE,RMSE,MSE,DAC,RAE,MAPE,RAE,RRSE");
            tsEvaluation.evaluateForecaster(forecaster,true,System.out);

            System.out.println(forecaster.getAlgorithmName());
            System.out.println(forecaster.toString());

            String forecastString = predsToString(forecast, numStepsToForecast);
            System.out.println("------------");
            System.out.println(forecastString);


            System.out.println(tsEvaluation.getPredictionsForTestData(1));
            System.out.println(tsEvaluation.getPredictionsForTrainingData(1));
            System.out.println(tsEvaluation.toSummaryString());

        } catch (Exception ex) {
            ex.printStackTrace();
            String msg = ex.getMessage().toLowerCase();
            if (msg.indexOf("not in classpath") > -1) {
                return;
            }
        }

    }



    private String predsToString(List<List<NumericPrediction>> preds, int steps) {
        StringBuffer b = new StringBuffer();

        for (int i = 0; i < steps; i++) {
            List<NumericPrediction> predsForTargetsAtStep =
                    preds.get(i);

            for (int j = 0; j < predsForTargetsAtStep.size(); j++) {
                NumericPrediction p = predsForTargetsAtStep.get(j);
                double[][] limits = p.predictionIntervals();
                b.append(p.predicted() + " ");
                if (limits != null && limits.length > 0) {
                    b.append(limits[0][0] + " " + limits[0][1] + " ");
                }
                b.append("   ").append(p.toString());
            }
            b.append("\n");
        }

        return b.toString();
    }
*/


}
